package com.ltmonitor.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ltmonitor.dao.IUserInfoDao;
import com.ltmonitor.entity.Department;
import com.ltmonitor.entity.UserInfo;
import com.ltmonitor.service.IUserInfoService;
/**
 * 用户信息服务
 * @author admin
 *
 */

@Service("userInfoService")
@Transactional(propagation = Propagation.REQUIRED) 
public class UserInfoService extends BaseService<Long, UserInfo> implements IUserInfoService {
	@Autowired
	private IUserInfoDao userInfoDao;
	
	
	public UserInfo getUserInfoByLoginName(String loginName)
	{

		String hsql = "from UserInfo where loginName = ? and userState <> ? and deleted = ?";

		UserInfo user = (UserInfo) this.userInfoDao.find(hsql,
				new Object[] { loginName, UserInfo.STATE_SUSPEND, false });
		
		return user;
	} 
	
	/**
	 * 给用户分配部门权限，同时自动给拥有该部门的上级部门权限的用户分配该权限
	 * @param dep 部门
	 * @param userId 用户id 
	 */
	public void assignDepartmentToUser(Department dep, long userId)
	{
		if (dep.getParentId() > 0) {
			//查询出拥有该部门的所有上级部门权限的用户，自动分配给他们
			String hql = "select u from UserInfo u inner join u.departments f where u.deleted=? and f.entityId=? and f.entityId <> ?";

			List result = this.query(hql, new Object[] {
					false, dep.getParentId(), dep.getEntityId() });
			for (Object obj : result) {
				UserInfo u = (UserInfo) obj;
				u.getDepartments().add(dep);
				this.saveOrUpdate(u);
			}
		} else {
			UserInfo u = this.load(userId);
			u.getDepartments().add(dep);
			this.saveOrUpdate(u);
		}
	}
	
}
